package by.bsu.scs_bsu.html.tools;

import java.sql.ResultSet;
import java.sql.SQLException;

public class TableGenerator {
	
	private static final String TABLE_OP_TAG = "<table class='%s'>";
	private static final String TABLE_CL_TAG = "</table>";
	private static final String TH_OP_TAG = "    <th class='%s'>";
	private static final String TH_CL_TAG = "    </th>";
	private static final String TR_OP_TAG = "  <tr class='%s'>";
	private static final String TR_CL_TAG = "  </tr>";
	private static final String TD_OP_TAG = "    <td class='%s'>";
	private static final String TD_CL_TAG = "    </td>";
	//private static final String BR_TAG = "<br/>";
	private static final String NEW_LINE = "\r\n";
	
	private ResultSet resultSet;
	private StringBuilder output;
	private String [] headerNames = null;
	private String tableStyle;
	private int columnAmount;
	
	public TableGenerator(ResultSet resultSet, String tableStyle) throws SQLException {
		this.resultSet = resultSet;
		this.tableStyle = tableStyle;
		columnAmount  = resultSet.getMetaData().getColumnCount();
	}
	
	public TableGenerator(ResultSet resultSet, String tableStyle, String [] headerNames) throws SQLException {
		this.resultSet = resultSet;
		this.tableStyle = tableStyle;
		this.headerNames = headerNames;
		columnAmount  = resultSet.getMetaData().getColumnCount();
	}
	
	public String generateTable() throws SQLException {
		output = new StringBuilder();
		if(headerNames != null) {
			output.append(formTag(TABLE_OP_TAG, tableStyle));
			output.append(formTag(TR_OP_TAG, tableStyle));
			for(int i = 0; i < headerNames.length; i++) {
				output.append(formTag(TH_OP_TAG, tableStyle, Integer.toString(i)));
				output.append(headerNames[i]);
				output.append(TH_CL_TAG + NEW_LINE);
			}
			output.append(TR_CL_TAG + NEW_LINE);
		}
		int rowPointer = 0;
		while(resultSet.next()) {
			if(rowPointer == 1) {
				rowPointer --;
			}
			output.append(formTag(TR_OP_TAG, tableStyle, Integer.toString(rowPointer)));
			for(int i = 1; i <= columnAmount; i++) {
				output.append(formTag(TD_OP_TAG, tableStyle));
				output.append(resultSet.getObject(i).toString());
				output.append(TD_CL_TAG + NEW_LINE);
			}
			output.append(TR_CL_TAG + NEW_LINE);
		}
		output.append(TABLE_CL_TAG + NEW_LINE);
		return output.toString();
	}
	
	private String formTag(String tag, String ... paramArray) {
		StringBuilder paramString = new StringBuilder();
		for(String param: paramArray) {
			paramString.append(param);
		}
		
		return String.format(tag, paramString.toString()) + NEW_LINE;
	}

}
